In [18]:
# ================================================================
# LAB 13. NONLINEAR REGRESSION
#
# STAT 415/615 - Regression
#
# Topics:
#   1. Fitting a nonlinear regression model
#   2. Parameter estimates and significance tests
#   3. Convergence and residual sum of squares
#   4. Predicted values
#
# ================================================================


# ================================================================
# PART 0. PREPARATION
# ================================================================

# Import the required libraries.
#
# pandas: data manipulation
# numpy: numerical calculations
# scipy: nonlinear least squares and statistical tests
# matplotlib: graphs

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

from scipy.optimize import curve_fit
from scipy.stats import t


# Load the mtcars dataset, used in our previous labs.
#
# The dataset contains information about 32 automobiles,
# including fuel economy (mpg), weight (wt), and the
# number of cylinders (cyl).

mtcars = pd.read_csv(
    "https://raw.githubusercontent.com/vincentarelbundock/"
    "Rdatasets/master/csv/datasets/mtcars.csv",
    index_col=0
)

print(mtcars.head())
                    mpg  cyl   disp   hp  drat     wt   qsec  vs  am  gear  \
rownames                                                                     
Mazda RX4          21.0    6  160.0  110  3.90  2.620  16.46   0   1     4   
Mazda RX4 Wag      21.0    6  160.0  110  3.90  2.875  17.02   0   1     4   
Datsun 710         22.8    4  108.0   93  3.85  2.320  18.61   1   1     4   
Hornet 4 Drive     21.4    6  258.0  110  3.08  3.215  19.44   1   0     3   
Hornet Sportabout  18.7    8  360.0  175  3.15  3.440  17.02   0   0     3   

                   carb  
rownames                 
Mazda RX4             4  
Mazda RX4 Wag         4  
Datsun 710            1  
Hornet 4 Drive        1  
Hornet Sportabout     2  
In [19]:
# ================================================================
# PART 1. FITTING A NONLINEAR REGRESSION MODEL
# ================================================================

# We want to predict fuel economy using car weight
# and the number of cylinders.
#
# Consider the nonlinear regression model:
#
# log(mpg) = b0 + b1 * exp(b2 * wt + cyl) + error
#
# Here:
#
#   b0, b1, b2 are unknown regression parameters.
#   wt is the automobile's weight.
#   cyl is the number of cylinders.
#
# The model is nonlinear in the parameter b2.
#
# Therefore, ordinary linear regression cannot be
# used to estimate all three parameters.
#
# Instead, we minimize the residual sum of squares
# numerically using nonlinear least squares.


# ------------------------------------------------
# 1A. Define the nonlinear regression function
# ------------------------------------------------

# The function takes two predictors and three parameters.
#
# curve_fit() will estimate b0, b1, and b2.

def nonlinear_model(X, b0, b1, b2):

    wt, cyl = X

    return b0 + b1 * np.exp(b2 * wt + cyl)


# Define the response and predictors.

Y = np.log(mtcars["mpg"].to_numpy())

wt = mtcars["wt"].to_numpy()

cyl = mtcars["cyl"].to_numpy()


# ------------------------------------------------
# 1B. Estimate the parameters
# ------------------------------------------------

# Nonlinear least squares requires initial estimates
# of the unknown parameters.
#
# Unlike linear regression, the numerical algorithm
# may converge to different solutions depending on
# the initial estimates.
#
# We use starting values near those obtained in the
# original R lab to facilitate convergence.
#
# The parameter estimates are obtained by minimizing:
#
# SSE = sum((Yi - f(Xi; b0, b1, b2))^2)


initial = [3.2, -0.00005, 0.29]

params, covariance = curve_fit(
    nonlinear_model,
    (wt, cyl),
    Y,
    p0=initial,
    maxfev=10000
)


# Extract the estimated parameters.

b0, b1, b2 = params

print("\nNONLINEAR REGRESSION")

print("b0 =", b0)
print("b1 =", b1)
print("b2 =", b2)


# ------------------------------------------------
# 1C. Residual sum of squares
# ------------------------------------------------

# Calculate the fitted values of log(mpg).

Yhat = nonlinear_model(
    (wt, cyl),
    b0, b1, b2
)


# Calculate the residuals.

residuals = Y - Yhat


# Calculate the residual sum of squares.

SSE = np.sum(residuals ** 2)

print("\nResidual sum of squares:", round(SSE, 4))


# The residual degrees of freedom equal:
#
#     n - k
#
# where k = 3 is the number of estimated parameters.

n = len(Y)

k = len(params)

df = n - k


# Residual standard error.

RSE = np.sqrt(SSE / df)

print("Residual standard error:", round(RSE, 4))
print("Residual degrees of freedom:", df)
NONLINEAR REGRESSION
b0 = 3.187779038356398
b1 = -5.119729548511079e-05
b2 = 0.28895010923225056

Residual sum of squares: 0.7844
Residual standard error: 0.1645
Residual degrees of freedom: 29
In [20]:
# ================================================================
# PART 2. PARAMETER ESTIMATES AND SIGNIFICANCE TESTS
# ================================================================

# The covariance matrix returned by curve_fit()
# provides approximate variances and covariances
# of the estimated regression parameters.
#
# The standard errors are the square roots of
# its diagonal elements.
#
# For each parameter, we test:
#
#     H0: beta_j = 0
#
# using the approximate t-statistic:
#
#              estimated beta_j
#     t = ----------------------------
#          SE(estimated beta_j)
#
# The tests use n - k residual degrees of freedom.
#
# These are approximate tests based on the local
# linearization of the nonlinear regression model.


# ------------------------------------------------
# 2A. Standard errors
# ------------------------------------------------

SE = np.sqrt(np.diag(covariance))


# ------------------------------------------------
# 2B. t-statistics and p-values
# ------------------------------------------------

tvalues = params / SE

pvalues = 2 * t.sf(
    np.abs(tvalues),
    df
)


# ------------------------------------------------
# 2C. Display the regression summary
# ------------------------------------------------

summary = pd.DataFrame({
    "Estimate": params,
    "Std. Error": SE,
    "t value": tvalues,
    "p-value": pvalues
}, index=["b0", "b1", "b2"])

print("\nPARAMETER ESTIMATES")

print(summary.round(6))
PARAMETER ESTIMATES
    Estimate  Std. Error    t value   p-value
b0  3.187779    0.041363  77.069025  0.000000
b1 -0.000051    0.000025  -2.011689  0.053627
b2  0.288950    0.105312   2.743761  0.010309
In [21]:
# ================================================================
# PART 3. PREDICTION
# ================================================================

# Predicted values are calculated by substituting
# the estimated parameters into the regression function.
#
# Our model predicts log(mpg).
#
# Therefore:
#
#     log(mpg)_predicted = b0 + b1 * exp(b2*wt + cyl)
#
# Exponentiating gives predictions on the mpg scale.
#
# Note that exp(predicted log(mpg)) is not generally
# an unbiased estimate of the conditional mean mpg.
# It is the exponentiated fitted log response.


# ------------------------------------------------
# 3A. Predicted log(mpg)
# ------------------------------------------------

log_mpg_predicted = nonlinear_model(
    (wt, cyl),
    *params
)


# ------------------------------------------------
# 3B. Predicted mpg
# ------------------------------------------------

mpg_predicted = np.exp(log_mpg_predicted)


# Display observed and predicted values.

predictions = pd.DataFrame({
    "Observed mpg": mtcars["mpg"],
    "Predicted log(mpg)": log_mpg_predicted,
    "Predicted mpg": mpg_predicted
})

print("\nOBSERVED AND PREDICTED VALUES")

print(predictions.round(3))
OBSERVED AND PREDICTED VALUES
                     Observed mpg  Predicted log(mpg)  Predicted mpg
rownames                                                            
Mazda RX4                    21.0               3.144         23.191
Mazda RX4 Wag                21.0               3.140         23.113
Datsun 710                   22.8               3.182         24.102
Hornet 4 Drive               21.4               3.135         23.000
Hornet Sportabout            18.7               2.775         16.045
Valiant                      18.1               3.132         22.912
Duster 360                   14.3               2.760         15.794
Merc 240D                    24.4               3.181         24.065
Merc 230                     22.8               3.181         24.067
Merc 280                     19.2               3.132         22.919
Merc 280C                    17.8               3.132         22.919
Merc 450SE                   16.4               2.693         14.777
Merc 450SL                   17.3               2.739         15.477
Merc 450SLC                  15.2               2.733         15.376
Cadillac Fleetwood           10.4               2.492         12.086
Lincoln Continental          10.4               2.456         11.660
Chrysler Imperial            14.7               2.473         11.855
Fiat 128                     32.4               3.183         24.107
Honda Civic                  30.4               3.183         24.127
Toyota Corolla               33.9               3.183         24.120
Toyota Corona                21.5               3.182         24.097
Dodge Challenger             15.5               2.766         15.891
AMC Javelin                  15.2               2.776         16.055
Camaro Z28                   13.3               2.725         15.255
Pontiac Firebird             19.2               2.724         15.244
Fiat X1-9                    27.3               3.183         24.116
Porsche 914-2                26.0               3.183         24.109
Lotus Europa                 30.4               3.183         24.130
Ford Pantera L               15.8               2.806         16.550
Ferrari Dino                 19.7               3.142         23.145
Maserati Bora                15.0               2.760         15.794
Volvo 142E                   21.4               3.182         24.084
In [22]:
# ================================================================
# PART 4. VISUALIZATION
# ================================================================

# Plot observed mpg against predicted mpg.
#
# Points close to the diagonal line indicate
# good agreement between observed and predicted
# fuel economy.
#
# The dashed line represents perfect predictions.


plt.figure(figsize=(7, 6))

plt.scatter(
    mtcars["mpg"],
    mpg_predicted
)

limits = [
    min(mtcars["mpg"].min(), mpg_predicted.min()),
    max(mtcars["mpg"].max(), mpg_predicted.max())
]

plt.plot(
    limits,
    limits,
    "k--"
)

plt.xlabel("Observed mpg")
plt.ylabel("Predicted mpg")
plt.title("Nonlinear Regression: Observed vs Predicted")

plt.grid(alpha=0.3)

plt.show()
No description has been provided for this image
In [ ]:
# ================================================================
# PART 5. EXPORT THE NOTEBOOK TO HTML AND IPYNB
# ================================================================

# This section saves the current Google Colab notebook
# in two formats:
#
# HTML:
#   A readable document containing the Python code,
#   explanatory comments, tables, and graphical output.
#
# IPYNB:
#   An executable notebook that can be opened and
#   edited in Google Colab or Jupyter.
#
# Run this section AFTER executing the previous cells.
#
# Both files will be downloaded to your computer.
# Your browser's download settings determine the folder
# where the files are saved.


from google.colab import _message, files
from nbconvert import HTMLExporter
import nbformat
import json


# Retrieve the current Google Colab notebook.

notebook = _message.blocking_request(
    "get_ipynb",
    timeout_sec=60
)["ipynb"]


# Convert it to standard Jupyter notebook format.

nb = nbformat.reads(
    notebook if isinstance(notebook, str)
    else json.dumps(notebook),
    as_version=4
)


# Specify the common filename.

filename = "Py Lab 13 - Nonlinear Regression"


# ------------------------------------------------
# Save the executable Jupyter notebook
# ------------------------------------------------

with open(filename + ".ipynb", "w", encoding="utf-8") as f:
    nbformat.write(nb, f)


# ------------------------------------------------
# Convert the notebook to HTML
# ------------------------------------------------

html, resources = HTMLExporter().from_notebook_node(nb)


# Save the HTML document.

with open(filename + ".html", "w", encoding="utf-8") as f:
    f.write(html)


# ------------------------------------------------
# Download both files
# ------------------------------------------------

files.download(filename + ".html")

files.download(filename + ".ipynb")


# ================================================================
# END OF LAB 13
# ================================================================
In [ ]: